package com.ruoyi.web.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.by.health.component.EmpWeChatTokenService;
import com.ruoyi.by.health.domain.WechatLoginEmp;
import com.ruoyi.by.health.domain.entity.ByhealthEmployee;
import com.ruoyi.by.health.domain.entity.ByhealthLotteryOutcome;
import com.ruoyi.by.health.domain.form.WechatRegisteredForm;
import com.ruoyi.by.health.service.IByhealthEmployeeService;
import com.ruoyi.by.health.service.IByhealthLotteryOutcomeService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.wechat.domain.WechatUser;
import com.ruoyi.wechat.pojo.WxMpAuthorizationUrl;
import com.ruoyi.wechat.service.IWeChatBaseService;
import com.ruoyi.wechat.service.IWechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author cj
 */
@Api(value = "微信接口", tags = "微信接口")
@RestController
@RequestMapping("/wechat/base")
public class WeChatBaseController {

    @Autowired
    IWeChatBaseService weChatBaseService;
    @Autowired
    IByhealthEmployeeService employeeService;
    @Autowired
    IWechatUserService wechatUserService;
    @Autowired
    EmpWeChatTokenService weChatTokenService;
    @Autowired
    SysLoginService wechatLoginService;
    @Autowired
    IByhealthLotteryOutcomeService lotteryOutcomeService;
    private static final Logger log = LoggerFactory.getLogger(WeChatBaseController.class);

    @PostMapping("/registered")
    @ApiOperation(value = "微信用户注册")
    public AjaxResult driverRegistered(@RequestBody WechatRegisteredForm wechatRegisteredForm) {
        String phone = wechatRegisteredForm.getPhone();
        String miniCode = wechatRegisteredForm.getMiniCode();
        String empName = wechatRegisteredForm.getEmpName();
        String empCode = wechatRegisteredForm.getEmpCode();
        log.info("driverRegistered:miniCode={},empName:{},phone:{},empCode:{}",
                miniCode, empName, phone, empCode);
        return employeeService.registerEmployee(wechatRegisteredForm);
    }
    @PostMapping("/applogin")
    @ApiOperation("applogin")
    AjaxResult applogin(@RequestBody WechatRegisteredForm wechatRegisteredForm, HttpServletResponse response) {
        //根据 code 获取 openId
        String appOpenid = weChatBaseService.miniappLogin(wechatRegisteredForm.getMiniCode());
        //WechatUser wechatUser = getUserByOpenid(openid);
        ByhealthEmployee employee = employeeService.selectEmployeeByAppOpenId(appOpenid);
        if (Objects.nonNull(employee)) {
            Set<String> perms = new HashSet<String>();
            // 管理员拥有所有权限
            perms.add("*:*:*");
            WechatLoginEmp loginEmp = new WechatLoginEmp(employee, perms);
            List<ByhealthLotteryOutcome> lotteryOutcomeList = lotteryOutcomeService.getLotteryOutcomeByEmpId(employee.getEmpId());
            loginEmp.setLotteryOutcomes(lotteryOutcomeList);
            //wechatLoginService.wechatLogin(loginEmp);
            String token = weChatTokenService.createToken(loginEmp);
            response.addHeader("token", token);
            loginEmp.setAuthToken(token);
            return AjaxResult.success(loginEmp);
        } else {
            return AjaxResult.error(1, "未查询到信息请先绑定账号");
        }
    }




    /**
     * 前端获取网页认证的链接
     *
     * @param wxMpAuthorizationUrl 参数实体
     * @return 认证授权url
     */
    @PostMapping("/getWebAuthUrl")
    public String getWebAuthUrl(@RequestBody WxMpAuthorizationUrl wxMpAuthorizationUrl) {
        return weChatBaseService.getWebAuthUrl(wxMpAuthorizationUrl);
    }


    /**
     * 微信认证登录，系统中已存在则直接返回。否则入库
     *
     * @param code
     * @return
     */
    /*@GetMapping("/login/{code}")
    @ApiOperation("login")
    AjaxResult login(@PathVariable String code,HttpServletResponse response) {
        //根据 code 获取 openId
        String openid = weChatBaseService.webLogin(code);
        WechatUser wechatUser = getUserByOpenid(openid);
        response.addHeader("token",weChatTokenService.createToken(new WeChatLoginUser(wechatUser,null)));
        return AjaxResult.success(wechatUser);
    }*/
    @PostMapping("/login/{code}")
    @ApiOperation("login")
    AjaxResult login(@PathVariable String code, HttpServletResponse response) {
        //根据 code 获取 openId
        String openid = weChatBaseService.webLogin(code);
        ByhealthEmployee employee = employeeService.selectEmployeeByOpenId(openid);
        if (!Objects.isNull(employee)) {
            response.addHeader("token", weChatTokenService.createToken(new WechatLoginEmp(employee, null)));
            return AjaxResult.success(employee);
        } else {
            return AjaxResult.error("未查询到信息请注册");
        }
    }



    /**
     * 根据 code 获取 openid
     *
     * @param code 微信临时 code
     * @return
     */
    @GetMapping("/getOpenid/{code}")
    @ApiOperation("getOpenid")
    AjaxResult getOpenId(@PathVariable String code) {
        return weChatBaseService.webAuth(code);
    }


    /**
     * 返回前端跳转的首页，并在cookie和请求头同中放入token(包含用户请求)
     *
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/redirect/auth")
    @ApiOperation("回调授权接口")
    void redirectAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        System.out.println(code);
        System.out.println(state);
        String id = state.substring(0, 18);
        String appId = state.substring(18);
        //根据 code 获取 openId
//        String openid = weChatBaseService.webLogin(code);
        String openid = "1234567";
//        WechatUser wechatUser = getUserByOpenid(openid);
//        response.addHeader("token",weChatTokenService.createToken(new WeChatLoginUser(wechatUser,null)));
        response.sendRedirect("http://wechat.test.nofeel.club?openid=" + openid);
    }

    /**
     * 根据 openid 获取用户信息
     *
     * @param openid 当前公众号对应用户的账号
     * @return 返回值
     */
    private WechatUser getUserByOpenid(String openid) {
        WechatUser wechatUser = wechatUserService.selectWechatUserById(openid);
        if (wechatUser == null) {
            //查询用户信息并且入库
            JSONObject jsonObject = weChatBaseService.getUserInfo(openid);
            wechatUser = JSON.toJavaObject(jsonObject, WechatUser.class);
            wechatUserService.insertWechatUser(wechatUser);
        }
        return wechatUser;
    }

}
